/*
 * @Author: your name
 * @Date: 2022-01-21 22:16:17
 * @LastEditTime: 2022-01-21 22:18:27
 * @LastEditors: your name
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /goose/src/context/request.context.ts
 */
import { Request, Response } from 'express';
import { getNamespace } from 'node-request-context';
import { UserContext } from './user.context';

export class RequestContext {
  public id: number;
  public request: Request;
  public response: Response;

  /**
   * 请求上下文构造函数
   * @param request 请求对象
   * @param response 返回对象
   */
  constructor(request: Request, response: Response) {
    this.id = Math.random();
    this.request = request;
    this.response = response;
  }

  /**
   * 获取请求上下文
   */
  public static currentRequestContext(): RequestContext {
    const namespace = getNamespace('lantsang.iot');
    if (namespace) {
      try {
        const requestContext = namespace.get('tid');
        return requestContext;
      } catch (error) {
        console.log(error);
        return null;
      }
    }
  }

  /**
   * 获取当前请求
   */
  public static currentRequest(): Request {
    const requestContext = RequestContext.currentRequestContext();
    if (requestContext) return requestContext.request;
  }

  /**
   * 获取当前用户
   */
  public static currentUser(): UserContext {
    const requestContext = RequestContext.currentRequestContext();
    if (requestContext) return requestContext.request['user'];
  }
}
